﻿using LazyFieldDemo.Helpers;
using LazyFieldDemo.Models;
using LazyFieldDemo.ViewModels;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.Handlers;
using Orchard.Data;

namespace LazyFieldDemo.Drivers {
    public class AddressPartDriver : ContentPartDriver<AddressPart> {
        private readonly IRepository<Country> _countryRepository;
        public AddressPartDriver(IRepository<Country> countryRepository) {
            _countryRepository = countryRepository;
        }

        protected override string Prefix {
            get { return "Address"; }
        }

        protected override DriverResult Display(AddressPart part, string displayType, dynamic shapeHelper) {
            return ContentShape("Parts_Address", () => shapeHelper.Parts_Address());
        }

        protected override DriverResult Editor(AddressPart part, dynamic shapeHelper) {
            var viewModel = AddressViewModel.Map(part);
            return ContentShape("Parts_Address_Edit", () => shapeHelper.EditorTemplate(TemplateName: "Parts/Address", Model: viewModel, Prefix: Prefix));
        }

        protected override DriverResult Editor(AddressPart part, IUpdateModel updater, dynamic shapeHelper) {
            var viewModel = new AddressViewModel();
            if(updater.TryUpdateModel(viewModel, Prefix, null, null)) {
                AddressViewModel.Map(viewModel, part, _countryRepository);
            }
            return Editor(part, shapeHelper);
        }

        protected override void Exporting(AddressPart part, ExportContentContext context) {
            context.Element(part.PartDefinition.Name).SetAttributeValue("AddressLine1", part.AddressLine1);
            context.Element(part.PartDefinition.Name).SetAttributeValue("AddressLine2", part.AddressLine2);
            context.Element(part.PartDefinition.Name).SetAttributeValue("Zipcode", part.Zipcode);
            context.Element(part.PartDefinition.Name).SetAttributeValue("City", part.City);
            context.Element(part.PartDefinition.Name).SetAttributeValue("CountryCode", part.Country != null ? part.Country.Code : "");
        }

        protected override void Importing(AddressPart part, ImportContentContext context) {
            context.ImportAttribute(part.PartDefinition.Name, "AddressLine1", x => part.AddressLine1 = x);
            context.ImportAttribute(part.PartDefinition.Name, "AddressLine2", x => part.AddressLine2 = x);
            context.ImportAttribute(part.PartDefinition.Name, "Zipcode", x => part.Zipcode = x);
            context.ImportAttribute(part.PartDefinition.Name, "City", x => part.City = x);
            context.ImportAttribute(part.PartDefinition.Name, "CountryCode", x => part.Country = _countryRepository.Get(c => c.Code == x));
        }
    }
}